package cn.jietuo.juc.c_008_interview1;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/8
 * @description:
 */
public class T03 {

    private List<Integer> list = new ArrayList<>();

    private void add(Integer i) {
        list.add(i);
    }

    private Integer size() {
        return list.size();
    }

    public static void main(String[] args) {
        T03 t = new T03();
        Object lock = new Object();
        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t2启动");
                if (t.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2结束");
                // 通知t1继续执行
                lock.notify();
            }
        }, "t2").start();

        new Thread(() -> {
            synchronized (lock) {
                System.out.println("t1启动");
                for (int i = 0; i < 10; i++) {
                    t.add(i);
                    System.out.println("add:" + i);
                    if (t.size() == 5) {
                        lock.notify();
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
//                    try {
//                        TimeUnit.SECONDS.sleep(1);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        }, "t1").start();

    }
}
